package com.jule.robot.service;

import com.jule.core.jedis.StoredObjManager;
import com.jule.core.service.CronTaskManager;
import com.jule.core.service.ThreadPoolManager;
import com.jule.db.entities.RobotCapitalPoolConfigModel;
import com.jule.db.proxy.EntityProxy;
import com.jule.robot.dao.DBUtil;
import com.jule.robot.model.eenum.PlayTypeEnum;
import com.jule.teenpatti.base.dao.bean.RobotPool;
import com.jule.teenpatti.base.enums.RedisConst;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * 资金池redis缓存
 * @author ran.wang
 * @since 2018/11/5 16:28
 */
@Slf4j
public class PoolConfigService {

    public static final PoolConfigService OBJ = new PoolConfigService();

    public PoolConfigService init(){
        //30分钟定时加载
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()->loadFromDB(),5,30*60, TimeUnit.SECONDS);
        return this;
    }

    public void reset(){
        //重置资金池和杀量池
        Consumer<Object> resetPoolTask = obj -> {
            ThreadPoolManager.getInstance().addTask(()->resetPool());
        };

        CronTaskManager.CountDownTask task = new CronTaskManager.CountDownTask(0l, resetPoolTask);
        CronTaskManager.getInstance().addCountDownJob(task.getName(), "resetRobotKillPool", task, "0 0 0 * * ?");
    }

    private void loadFromDB(){
        log.warn("开始定时加载资金池配置");
        for (PlayTypeEnum game : PlayTypeEnum.values()){
            RobotCapitalPoolConfigModel model = DBUtil.selectByCapitalPool(String.valueOf(game.getGameId()));
            if (model == null){
                log.error("机器人资金池为空 game={}",game.getGameId());
                continue;
            }

            RobotPool config = new RobotPool();
            config.setId(model.getId());
            config.setPlayType(model.getPlayType());
            config.setTotalMoney(model.getTotalMoney());
            config.setInitTotalMoney(model.getInitTotalMoney());
            config.setInitKillPool(model.getInitKillPool());
            config.setInitRobotPool(model.getInitRobotPool());
            config.setFlowRate(model.getFlowRate());

            StoredObjManager.hset(RedisConst.ROBOT_POOL_CONFIG.getProfix()+model.getPlayType(), RedisConst.ROBOT_POOL_CONFIG.getField(),config);
        }
    }

    private void resetPool(){
        log.warn("开始定时重置杀量池");
        //重置资金池
        EntityProxy.OBJ.executeNativeUpdate( "update `robot_capital_pool_config` t set t.total_money = t.init_total_money ", null);

        //重新加载
        loadFromDB();

        //重置杀量池
        StoredObjManager.set(RedisConst.ROBOT_POOL_KILL_POOL.getProfix(),String.valueOf(0));

        //重置机器人资金池
        StoredObjManager.set(RedisConst.ROBOT_POOL_CURRENT_MONEY.getProfix(),String.valueOf(0));
    }

}
